package com.funny.learning.english;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import org.json.JSONArray;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.funny.learning.english.api.BaseAjaxCallBack.IAjaxCallbackMMK;
import com.funny.learning.english.api.Define;
import com.funny.learning.english.api.TiengAnhApi;
import com.funny.learning.english.db.HistoryDAO;
import com.funny.learning.english.model.GameEntity;

public class GameBaseActivity extends BaseActivity {

	protected String slugGame;

	protected String slugSubTopic;

	protected String slugTopic;
	
	protected String slugGameName;

	protected String slugSubTopicName;

	protected String slugTopicName;
	
	protected String thumbTopic;

	protected File mFile;

	protected Activity activity;

	protected ArrayList<GameEntity> mGameEntities = new ArrayList<GameEntity>();
	
	protected boolean isAnwser;
	
	protected int countCheckScreen = 0;
	protected int countAnwserCorrect = 0;

	protected HistoryDAO mHistoryDAO;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		mHistoryDAO = new HistoryDAO(this);

		activity = (GameBaseActivity) this;
		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			slugGame = bundle.getString(Define.INTENT_SLUG_GAME);
			slugSubTopic = bundle.getString(Define.INTENT_SLUG_SUB_TOPIC);
			slugTopic = bundle.getString(Define.INTENT_SLUG_TOPIC);
			thumbTopic = bundle.getString(Define.INTENT_THUMB_GAME);
			slugGameName = bundle.getString(Define.INTENT_SLUG_GAME_NAME);
			slugSubTopicName = bundle.getString(Define.INTENT_SLUG_SUB_TOPIC_NAME);
			slugTopicName = bundle.getString(Define.INTENT_SLUG_TOPIC_NAME);

			loadData();
		}
	}
	protected void loadData() {

		// base path
		String pathData = getFilesDir().getPath()
				+ File.separator + "Android" + File.separator + "dulieu"
				+ File.separator + slugTopic + "_" + slugSubTopic;

		mFile = new File(pathData);

		if (!mFile.exists()) {
			// chưa có dữ liệu download data mới
			TiengAnhApi.playGame(this, slugTopic, slugSubTopic, slugGame,
					ajaxCallbackMMK);
		} else {
			// Nếu dữ liệu đã có tiến hành lấy dữ liệu từ local và tiến hành
			// check time
			// Nếu time đã cũ => download data mới
			// Nếu time chưa cũ => chơi game

			// if(new){
			// TiengAnhApi.playGame(this, slugTopic, slugSubTopic, slugGame,
			// ajaxCallbackMMK);
			// }else{
			// //play game
			// }

			long lTime = readJsonInfoFile();

			long lCurrentTime = System.currentTimeMillis();

			Date time = convertLongToDate(lTime);
			Date currentTime = convertLongToDate(lCurrentTime);

			if ((currentTime.compareTo(time) < 0)
					|| (currentTime.compareTo(time) > 0)) {
				TiengAnhApi.playGame(this, slugTopic, slugSubTopic, slugGame,
						ajaxCallbackMMK);
			} else {
				if(mGameEntities.size() > 0){
					initSucess();
					
				}else{
					Toast.makeText(appication, "Khong co du lieu", 2000).show();
					onBackPressed();
					return;
				}
			}

		}

	}

	protected void initSucess() {
		
	}

	private Date convertLongToDate(long milliseconds) {
		try {
			Date date = new Date(milliseconds);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String sNewDate = sdf.format(date);
			date = sdf.parse(sNewDate);
			Log.d("++++++++++++", sNewDate);
			return date;
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;
	}

	private IAjaxCallbackMMK ajaxCallbackMMK = new IAjaxCallbackMMK() {

		@Override
		public <T> void handler(T t, int code) {
			// TODO Auto-generated method stub
			if (code == COMPLETE) {
				@SuppressWarnings("unchecked")
				final ArrayList<GameEntity> gameEntities = (ArrayList<GameEntity>) t;
				mGameEntities.clear();
				mGameEntities.addAll(gameEntities);
				createJsonInfoFile();
				new Handler().postDelayed(mRunnable, 1000);
			}
		}
	};

	private Runnable mRunnable = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			download();
		}
	};

	private long readJsonInfoFile() {
		File myFile = new File(mFile.getPath() + File.separator + "info.json");
		long time = 0l;
		try {
			FileInputStream fIn = new FileInputStream(myFile);
			BufferedReader myReader = new BufferedReader(new InputStreamReader(
					fIn));
			String line = null;
			StringBuffer stringBuffer = new StringBuffer();
			while ((line = myReader.readLine()) != null) {
				stringBuffer.append(line);
			}
			myReader.close();
			String json = stringBuffer.toString();

			JSONObject jsonObject = new JSONObject(json);
			JSONArray jsonArray = jsonObject.getJSONArray("data");
			time = jsonObject.optLong("time", 0l);
			mGameEntities.clear();
			for (int i = 0; i < jsonArray.length(); ++i) {
				JSONObject object = jsonArray.getJSONObject(i);
				GameEntity gameEntity = new GameEntity(object, slugTopic,
						slugSubTopic, slugGame);
				mGameEntities.add(gameEntity);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return time;
	}

	public String getPathImg(GameEntity gameEntity) {
		if (gameEntity.getUrl() == null)
			return null;
		return mFile.getPath() + File.separator + gameEntity.getUrl();
	}

	public String getPathSound(GameEntity gameEntity) {
		if (gameEntity.getLaudio() == null)
			return null;
		return mFile.getPath() + File.separator + gameEntity.getLaudio();
	}

	private void createJsonInfoFile() {
		try {
			if (!mFile.exists())
				mFile.mkdirs();

			JSONObject jsonObject = new JSONObject();

			JSONArray jsonArray = new JSONArray();
			for (int i = 0; i < mGameEntities.size(); ++i) {
				GameEntity entity = mGameEntities.get(i);
				jsonArray.put(entity.toJson());
			}
			jsonObject.put("data", jsonArray);
			jsonObject.put("time", System.currentTimeMillis());

			Log.d("+++++++++++++", jsonObject.toString());

			writeToFile(jsonObject.toString());
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}

	}

	private void writeToFile(String txt) {
		try {
			File myFile = new File(mFile.getPath() + File.separator
					+ "info.json");

			Log.d("++++++++++", myFile.getPath());
			if (myFile.exists())
				myFile.delete();

			myFile.createNewFile();
			FileOutputStream fOut = new FileOutputStream(myFile);
			OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
			myOutWriter.append(txt);
			myOutWriter.close();
			fOut.close();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

	private void download() {
		new DownloadAsyncTask().execute();
	}

	class DownloadAsyncTask extends AsyncTask<Void, String, Void> {
		private ProgressDialog mProgressDialog;

		@SuppressLint("InlinedApi")
		public DownloadAsyncTask() {
			Log.d("++++++++++", "DownloadAsyncTask");
			mProgressDialog = new ProgressDialog(activity,
					android.R.style.Theme_DeviceDefault_Dialog);
			mProgressDialog.setCancelable(false);
			mProgressDialog.setMessage("Downloading ....");
		}

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			Log.d("++++++++++", "doInBackground");
			for (int i = 0; i < mGameEntities.size(); ++i) {

				GameEntity gameEntity = mGameEntities.get(i);
				publishProgress(gameEntity.getName());
				if (!TextUtils.isEmpty(gameEntity.getUrl())) {
					String picture = "http://static.vietalo.com/"
							+ gameEntity.getUrl();
					downloadFile(picture, gameEntity.getUrl());
				}

				if (!TextUtils.isEmpty(gameEntity.getLaudio())) {
					String sound = "http://static.vietalo.com/mp3/"
							+ gameEntity.getLaudio();
					downloadFile(sound, gameEntity.getLaudio());
				}
			}
			return null;
		}

		@Override
		protected void onProgressUpdate(String... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
			mProgressDialog.setMessage(values[0]);
		}

		private void downloadFile(String uri, String name) {
			int count;
			try {
				// String uri = url;// "http://static.vietalo.com/" +
				// gameEntity.getUrl();
				URL url = new URL(uri);
				URLConnection conection = url.openConnection();
				conection.connect();

				// input stream to read file - with 8k buffer
				InputStream input = new BufferedInputStream(url.openStream(),
						8192);

				// Output stream to write file
				OutputStream output = new FileOutputStream(mFile.getPath()
						+ File.separator + name);

				byte data[] = new byte[1024];

				while ((count = input.read(data)) != -1) {
					output.write(data, 0, count);
				}

				// flushing output
				output.flush();

				// closing streams
				output.close();
				input.close();

			} catch (Exception e) {
				Log.e("Error: ", e.getMessage());
			}
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			Log.d("++++++++++", "onPreExecute");
			mProgressDialog.show();
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			Log.d("++++++++++", "onPostExecute");
			mProgressDialog.dismiss();
			if(mGameEntities.size() > 0){
				initSucess();
			}else{
				Toast.makeText(appication, "Khong co du lieu", 2000).show();
				onBackPressed();
			}
			
		}
	}
	
	protected void setTitle(String title){
//		tvTitle.setText(title);
	}
	
	protected void finishGame(){
		onBackPressed();
		Toast.makeText(activity,"Ban da hoan thanh nhom cau hoi nay!!!!",1000).show();
	}

}
